package com.demo.tika.config;

import org.apache.tika.Tika;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;

@Configuration
public class CustomTikaConfig {
    private final ResourceLoader resourceLoader;

    public CustomTikaConfig(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Bean
    public Tika tika() throws TikaException, IOException, SAXException {

        // 读取tika配置
        Resource resource = resourceLoader.getResource("classpath:tika-config.xml");
        InputStream inputStream = resource.getInputStream();

        TikaConfig config = new TikaConfig(inputStream);
        // 生成tika检测器
        Detector detector = config.getDetector();
        // 创建tika解析器
        Parser autoDetectParser = new AutoDetectParser(config);

        // 通过检测器和解析器生成tika对象
        return new Tika(detector, autoDetectParser);
    }

}
